//
//  CategoryNewViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 3/2/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "CategoryNewViewController.h"

@interface CategoryNewViewController ()

@end

@implementation CategoryNewViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.title = @"New Category";
    
    // Configure the save button
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
	self.navigationItem.rightBarButtonItem = saveButton;
    
    // Configure the cancel button
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
	self.navigationItem.leftBarButtonItem = cancelButton;
    
    
    // create error message alert views
    _missingCategoryError = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Category name cannot be blank" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    // create input fields
    
    // activity name text field
    CGRect frame = CGRectMake(10.0, 50.0, 300.0, 28.0);
    _categoryNameTextField = [[UITextField alloc] initWithFrame:frame];
    _categoryNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    _categoryNameTextField.textColor = [UIColor blackColor];
    _categoryNameTextField.font = [UIFont systemFontOfSize:17.0];
    //textField.placeholder = @"";
    _categoryNameTextField.backgroundColor = [UIColor clearColor];
    _categoryNameTextField.autocorrectionType = UITextAutocorrectionTypeYes;
    _categoryNameTextField.keyboardType = UIKeyboardTypeDefault;
    _categoryNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:_categoryNameTextField];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


#pragma mark -
#pragma mark Save and cancel operations

- (IBAction)save {
	
    // update the current value in the databbase, then return to the previous view
    NSLog(@"activity name %@",_categoryNameTextField.text);
    
    // if activity name and category are both not empty, then create a new activity in the database, else display an alert error message to the user
    if(_categoryNameTextField.text == NULL || [_categoryNameTextField.text isEqualToString:@""])
        [_missingCategoryError show];
    else
    {
        @try {
            
            // connect to db
            
            NSString *docsDir;
            NSArray *dirPaths;
            
            // Get the documents directory
            dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            
            docsDir = dirPaths[0];
            
            // Build the path to the database file
            _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
            
            NSFileManager *filemgr = [NSFileManager defaultManager];
            
            // check to see if database already exists...
            if ([filemgr fileExistsAtPath: _databasePath ] == YES)
            {
                // open database
                if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
                {
                    NSLog(@"An error has occured when trying to open the database");
                }
                
                char *errMsg;
                
                // Add new category
                NSString *insert_category = [NSString stringWithFormat:@"INSERT INTO categories (name) VALUES ('%@')",_categoryNameTextField.text];
                const char *insert_category_const = [insert_category UTF8String];
                if (sqlite3_exec(_database, insert_category_const, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert category: %s",errMsg);
                
            }
            else
            {
                NSLog(@"Error: database could not be found in ActivityNewViewController");
            }
        }
        
        @catch (NSException *exception) {
            NSLog(@"An exception occured: %@", [exception reason]);
        }
        @finally {
            // close the database connection
            sqlite3_close(_database);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (IBAction)cancel {
    // return to the previous view, without saving
    [self.navigationController popViewControllerAnimated:YES];
}



@end
